let jwt = require('jsonwebtoken')
let Users = require('./../model/users')

//生成token令牌函数，uid为用户id，scope为权限等级(类型为数字，内部约定) 1超级管理员 2管理员 3人员 4浏览者
let generateToken = function(_id, mobile, password) {
    const { secretKey, expiresIn } = global.security
    // let defined = _id  + ',' + mobile + ',' + password;
    let defined = {
        _id,mobile,password
    }
    //第一个参数为用户信息的js对象，第二个为用来生成token的key值，第三个为配置项
    const token = jwt.sign({
        defined
    },secretKey,{
        expiresIn
    })
return token
} 

function VerifyToken (token) {
        const { secretKey, expiresIn } = global.security;
        return jwt.verify(token.split(' ')[1], secretKey,(error, cb)=>{
            console.log(error, cb, 'error')
            if (error || !cb) {
                return {
                    code: '1',
                    msg: '登录过期，请重新登录',
                    value: ''
                }
            } else {
                return {
                    code: '0',
                    msg: 'token解析成功',
                    value: cb.defined
                }
            }
        })
}

let autoToken = async (ctx, next) => {
    let auth = this.VerifyToken(ctx.request.get('authorization'))
    if (!auth || auth.code === '1') {
        ctx.body = new resModel.Due();
    } else {
        console.log('用户账号_id:' + auth.value._id)
        let user = await Users.findById(auth.value._id);
        if (!user) {
            ctx.body = new resModel.Def('该用户不存在');
        } else {
            ctx.auth = auth.value; // {_id: '', mobile:''}
            await next()
        }
    }
}

let mongoError = function(ctx, next, error) {
    ctx.body = {
        code: global.returnData.server.code,
        msg: error.message,
        data: ''
    }
}

class VerifyField {
    constructor(fied) {
        this.verifyFied = fied;
    }
    async getField(ctx, next) {
        let body = ctx.request.body;
        let tip = '';
        for (let i=0;i<this.verifyFied.length;i++) {
            let item = this.verifyFied[i];
            if (!body[item.name]) {
                tip = item.msg;
                break;
            }
        }
        if (tip) {
            ctx.body = {
                code: global.returnData.def.code,
                msg: tip,
                data: ''
            }
        } else {
            await next()
        }
    }
}



exports.generateToken = generateToken;
exports.mongoError = mongoError;
exports.VerifyToken = VerifyToken;
exports.VerifyField = VerifyField;
exports.autoToken = autoToken;